<?php
namespace app\index\controller;

use think\Controller;

use app\index\model\User as UserModel;
use app\index\model\Deallist as DLModel;
use app\index\model\Businesscenter as BCModel;
use app\index\model\Account as AccountModel;
use app\index\model\Setting as STModel;
use think\Session;

class Business extends  Base{

    //用户登录展示页面
    public function index(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        //实例化模型
        $BCmodel = new BCModel();

        $data = $BCmodel->order('Business_level')->select();

        $this->assign('data',$data);


        return $this->fetch();
    }
    //报单中心申请页面展示
    public function businessCenter_apply(){


        $UserID = Session::get('userid');
        $UserName = Session::get('username');
        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);


        return $this->fetch();
    }

    public function businessCenter_applyForm(){


        $UserID = Session::get('userid');
        $UserName = Session::get('username');
        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        $BusinessLevel = input('post.');


        //单个帐号一次只能申请一个报单中心,搜索一波
        $UserBC = new BCModel();
        $CheckOldBC = $UserBC->where([
            'user_id' => $UserID,
            'status'=>['eq',1]
        ])->find();

        if($CheckOldBC){
            if($CheckOldBC['Business_level'] < $BusinessLevel['businesslevel'] ){
                //已有的报单中心比申请的级别还高
                $this->error("申请的报单中心级别错误！");
            }else if($CheckOldBC['Business_level'] = $BusinessLevel['businesslevel']){
                //申请了同样级别的报单中心
                $this->error("申请的报单中心级别错误！");
            }
        }


        //正常申请报单中心

       /* array(1) {
            ["businesslevel"] => string(1) "1"
        }*/

       //检测是否达到报单中心申请资格
       if($BusinessLevel['businesslevel'] == 1){
           //申请一级报单中心
           //echo "申请一级报单中心";

           $UserDealList = new DLModel();
           $CheckUserDealListData = $UserDealList->where([
               'user_id' => $UserID,
               'deal_price' => ['EQ',96000]
           ])->find();

           if($CheckUserDealListData){
              //有资格
             $UserBC = new BCModel();
             $UserBC->data([
                 'user_id' => $UserID,
                 'user_name' =>$UserName,
                 'Business_level' =>$BusinessLevel['businesslevel']
             ]);

             $Res = $UserBC->save();
             if($Res){
                  $this->success('申请成功！！！等待审核中。。。');
             }else{
                 $this->error('申请失败!!!');
             }

           }else{
               //没有资格
               $this->error('您的有效报单中，没有金额达到96000的账单，无法申请！！！');
           }

       }else if($BusinessLevel['businesslevel'] == 2){
           //申请二级报单中心
          // echo "申请二级报单中心";

           $UserDealList = new DLModel();
           $CheckUserDealListData = $UserDealList->where([
               'userid' => $UserID,
               'deal_price' => ['EGT',48000]
           ])->find();

           if($CheckUserDealListData){
               //有资格
               $UserBC = new BCModel();
               $UserBC->data([
                   'user_id' => $UserID,
                   'user_name' =>$UserName,
                   'Business_level' =>$BusinessLevel['businesslevel']
               ]);

               $Res = $UserBC->save();
               if($Res){
                   $this->success('申请成功！！！等待审核中。。。');
               }else{
                   $this->error('申请失败!!!');
               }

           }else{
               //没有资格
               $this->error('您的有效报单中，没有金额达到48000的账单，无法申请！！！');
           }


       }


    }



    //报单申请页面展示
    public function business_apply(){

        $Info = input('param.');


        $UserID = Session::get('userid');
        $UserName = Session::get('username');
        //dump($UserInfo);die;
//        $CenterID = ($UserInfo['centerid'] > 0 )? $UserInfo['centerid'] : 0;
        $CenterID = ($Info) ? $Info['centerid'] : 0;



        $SystemSetting = new STModel();
        $SystemSettingData = $SystemSetting->where('id',1)->find();
        //dump($UserInfo);die;
        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);
        $this->assign('centerid',$CenterID);
        $this->assign('list_base_money',$SystemSettingData['limit_deallist_money']);

        return $this->fetch();

    }

    //报单申请页面表单
    public function business_applyForm(){

        $UserID = Session::get('userid');
        $Bussiness_applyInfo = input('post.');



//        array(6) {
//            ["list_id"] => string(2) "20"
//            ["list_money"] => string(3) "123"
//            ["business_center_num"] => string(1) "0"
//            ["list_des"] => string(3) "123"
//            ["user_name"] => string(5) "admin"
//            ["user_id"] => string(2) "20"
//         }



        if($Bussiness_applyInfo['user_id'] == $Bussiness_applyInfo['list_id']){
            //普通报单方式

            //实例化系统设置表
            $SystemSetting = new STModel();
            $SystemSettingData = $SystemSetting->where('id',1)->find();


            $ListMoney = $Bussiness_applyInfo['list_money']*$SystemSettingData['limit_deallist_money'];
            $ListId = $Bussiness_applyInfo['list_id'];
            $UserAccount = new AccountModel();
            $AccountData = $UserAccount->where('user_id',$ListId)->find();
            $Cash = $AccountData['cash'];
            $AllPay = $AccountData['allpay'];
            $Id = $AccountData['user_id'];
            if(($AllPay+$ListMoney) > 96000 ){

                $this->error('您的总账户已经达到了'.$AllPay.'元。超过上限96000了,请减少倍数');

            }
            if(($ListMoney) > $Cash ){

                $this->error('您的余额不足'.$Cash.'元。');

            }
            $newCash = $Cash-$ListMoney;
            $tempMoney = $AccountData['temp_money'];
            $newtempMoney = $ListMoney+$tempMoney;
            $Result  = $UserAccount->save([

                'temp_money' => $newtempMoney,
                'cash' => $newCash,
                'allpay' => $AllPay
            ],['user_id' => $Id]);
            if($Result){
                //跟新成功
                $this->success("报单成功！！！");
            }else{
                //更新失败
                $this->error('报单失败！！！');
            }

            //暂时不用
            $ListDes = $Bussiness_applyInfo['list_des'] ? $Bussiness_applyInfo['list_des'] : '0';

            //存入数据库

            $dlmodel = new DLModel();

            $dlmodel->data([

                'User_id' => $Bussiness_applyInfo['user_id'],
                'deal_price' => $ListMoney,
                'Business_Center_id' => $Bussiness_applyInfo['business_center_num'],
                'description' => $ListDes
            ]);
            $Res = $dlmodel->save();


            //dump($Res);die;
            if($Res){
                //保存成功
                $this->success('申请成功','Come/index');
            }else{
                $this->error('修改失败');
            }
        }else{
            //为他人报单，冻结当前用户账户，他人账户账单增加，多扣除百分之5的手续费

            $SystemSetting = new STModel();
            $SystemSettingData = $SystemSetting->where('id',1)->find();


            $ListMoney = $Bussiness_applyInfo['list_money']*$SystemSettingData['limit_deallist_money'];


            $PayManID = $Bussiness_applyInfo['user_id'];
            $UserAccount = new AccountModel();
            $AccountData = $UserAccount->where('user_id',$PayManID)->find();
            $GoldCoin = $AccountData['gold_coin'];

            //算出对冲的百分之5
            $Theft = $SystemSettingData['deal_list_for_other']*$ListMoney;

            //账单一共要付出的金币
            $ListPayCoin = $ListMoney+$Theft;


            //新的金币
            $NewGoldCoin = $GoldCoin - $ListPayCoin ;

            if(($GoldCoin - $ListPayCoin) > 0){

                //金币够的，可以报单，冻结报单的金币
                $PayUserData = $AccountData->save([
                    'temp_gold_coin' => $ListPayCoin,
                    'gold_coin' => $NewGoldCoin,
                ],['user_id' => $PayManID ]);

                if($PayUserData){
                    //当前金币账户已冻结,插入目标账户的订单
                    $ListUserDealList =  new DLModel();
                    $ListUserDealList->data([
                        'User_id' => $Bussiness_applyInfo['list_id'],
                        'deal_price' => $ListMoney,
                        'Business_Center_id' => $Bussiness_applyInfo['business_center_num'],
                        'description' => $Bussiness_applyInfo['list_des']
                    ]);
                    $ListUserData = $ListUserDealList->save();
                    if($ListUserData){
                        //目标用户插入成功
                        $this->success('申请成功','Come/index');
                    }else{
                        //目标用户插入失败
                        $this->error('报单失败！');
                    }
                }
            }else{
                //金币不够，无法为其他用户报单
                $this->error("当前账户个".$GoldCoin."金币,无法为目标用户支付含手续费的".$Theft."共".$ListPayCoin."个金币！");
            }
        }


    }

//    public function b(){
//        return $this->fetch();
//    }


    //报单 账单展示

    public function business_list(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        //实例化模型

        $dlmodel = new DLModel();

        //每次进账单表就更新当前用户的积分
        $ScoreData = $dlmodel->where([
            'score_status' => ['EQ',0],
            'status' => ['EQ',1],
            'user_id' => $UserID
        ])->select();

        //准备增加的积分
        $PlusScore = 0;

        //取出设置中的返还积分
        $SettingModel = new STModel();
        $SettingData = $SettingModel->where('id',1)->find();

        $DealListBack = $SettingData['deal_list_back'];
        //dump($ScoreData);die;
        foreach($ScoreData as $value){
            $PlusScore += ($value['deal_price']*$DealListBack);
        }

        //更新当前用户账单表积分状态
        foreach($ScoreData as $v){
            $dlmodel->save([
                'score_status' => 1,
                'status' => 1
            ],['id'=> $v['id']]
            );
        }

        $UserAccount = new AccountModel();
        //取出当前用户表总积分
        $UserAccountData = $UserAccount->where('user_id',$UserID)->find();
        $OldAccountScore = $UserAccountData['allscore'];
        $OldScore = $UserAccountData['score'];
        $NewScore = $PlusScore + $OldScore;
        //更新当前用户账户表的当前积分跟总积分
        $NewAccountScore = $OldAccountScore + $PlusScore;

        $Res = $UserAccount->save([
            'score' => $NewScore,
            'allscore' => $NewAccountScore,

        ],['user_id'=> $UserID]);

        //dump($Res);die;

        if(!$Res){
            echo "<script type = 'javascript'>".' '."alert('用户账户积分更新失败')</script>";
        }

        //账单表展示
        $data = $dlmodel->where('user_id',$UserID)->order('create_time DESC')->paginate(10);

        //dump($data);die;
        $page = $data->render();
        $total = $data->total();
        $count = $data->count();

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('total',$total);
        $this->assign('count',$count);



        return $this->fetch();
    }

    //输入id显示用户名
    public function  applyname(){

        $RegisterName = input('post.');
        $RegName= trim($RegisterName['element_name']);
        //dump($RegName);
        //file_put_contents('3.txt',$RegName,FILE_APPEND);

        $User = new UserModel();
        $Res= $User->where('id',$RegName)->find();
        //dump($Res);die;
        $userNAME = $Res['username'];
        //file_put_contents('4.txt',$userNAME,FILE_APPEND);
        if($userNAME){
            //名字存在
            
            return json_encode($userNAME);
        }else{
            //名字不存在
            return json_encode(0);
        }
    }
    public function  pic(){
        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);
        return $this->fetch();
    }
    public function  picdata(){
        $UserID = Session::get('userid');
        $UserModel = new UserModel();
        $a = $UserModel->select();
        if (empty($a)) {
            $data['code']=1;
        }else{
            $data['code']=0;
            $b = json_decode(json_encode($a),true);
            $idStr = '';
            $list = $this->formatTree($b,0,$idStr);
            $aa['children'] = $list;
            $data['data'] = $aa;
        }
        echo json_encode($data);die;
    }
    /**
     * 格式化数据为树形结构
     * @return [type] [description]
     */
    function formatTree($relations,$pid,$idStr){
        $list = array();
        foreach ($relations as $key => $relation) {
            if(intval($relation['pid'])==$pid){
                $result = $this->formatTree($relations,$relation['id'],$idStr);
                $result && $data['children'] = $result;
                $data['admin_user_id'] = $relation['id'];
                $data['name'] = $relation['username'];
                $list[] = $data;
                $idStr .= ','.$data['admin_user_id'];
            }
            unset($data);
        }
        return $list;
    }
}
